package obj;

import data.DataHelper;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Headset {
    public static final String NA = "уточняйте";

    public static final String HEADSETS_PATH = "data/headsets/headsets.%s.txt";
    public static final String BASE_URL = "http://extramobi.ru/product/headset_";

    public String name;
    public String brandName;
    public String type;
    public String vendor = NA;
    public String model = NA;
    public String pin = NA;
    public int price;
    public int oldPrice;
    public int count;
    public String[] devices;
    public String url;
    public List<String> deviceURLs;

    public static Headset parseHeadset(String line) {
        String[] fields = line.split(";");
        Headset headset = new Headset();
        headset.name = fields[0];
        headset.devices = fields[1].split(",");
        headset.brandName = headset.vendor = fields[2];
        headset.model = fields[3];
        headset.type = fields[4];
        headset.pin = fields[5];
        headset.price = Integer.valueOf(fields[6].trim());
        headset.oldPrice = Integer.valueOf(fields[7].trim());
        headset.count = Integer.valueOf(fields[8].trim());
        headset.url = DataHelper.codeInURL(BASE_URL + headset.name).toLowerCase();
        headset.deviceURLs = new ArrayList<String>();
        for (String model : headset.devices) {
            String deviceUrl = DataHelper.codeInURL(BASE_URL + headset.brandName + "_" + model);
            headset.deviceURLs.add(deviceUrl);
        }
        return headset;
    }

    public static Headset parseHeadset(String line, int lineNum) {
        try {
            return parseHeadset(line);
        } catch (Exception e) {
            throw new IllegalStateException("Line : " + lineNum, e);
        }
    }

    public static List<Headset> parseHeadsets(String brandName, double coef) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(String.format(HEADSETS_PATH, brandName.replace("Sony Ericsson", "se"))));
        List<Headset> headsets = new ArrayList<Headset>();
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.contains("﻿")) {
                line = line.replace("﻿", "");
            }
            Headset headset = parseHeadset(line);
            headsets.add(headset);
        }
        return headsets;
    }
}
